import socket
import binascii
import select
import time
import asyncio
import threading
import queue
import multiprocessing
from select import*
from util.DLT698 import GetRequestNormal, SetRequestNormal, ActionRequest,GetCompletionFra,GetResponseNormal,ServiceJudgment
from util.Encoder import *
from util.MeterDoc import *
from util.tool import *
from util.protocol_dx import Protocol_Dx
from test_ProtocolConsistency.test_GET  import*
from test_ProtocolConsistency.test_AppLayer import*
class server():
    def __init__(self) -> None:
        self.input_queue=multiprocessing.Queue(50)
        self.rev_queue = multiprocessing.Queue(50)
    def server_program(self):
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = '192.168.1.99'  
        port = 8000
        ip_port = (host,port)
        server_socket.bind(ip_port)
        server_socket.listen(5)
        client_socket, addr =  server_socket.accept()
        self.set_client_socket(client_socket)
        # print("连接地址:{}".format(addr))
        # data =self.client_socket.recv(1024)
        # hex_data = binascii.hexlify(data).decode('ascii')
        # print("接收的报文:{}".format(hex_data))
        # apdu=self.dedcode(hex_data)["apdu"]
        # self.lginh(apdu)
        # se = AppLayer(client_socket=self.client_socket)
        # se.SR()
    async def input_id(self):
        loop = asyncio.get_event_loop()
        def input_thread():
            user_input = input("Enter task_id: ")
            loop.call_soon_threadsafe(self.input_queue.put_nowait, user_input)
        hread = threading.Thread(target=input_thread)
        hread.start()
        return await loop.run_in_executor(None, self.input_queue.get)
    async def rev(self):
        while True:
            data =self.client_socket.recv(1024)
            hex_data = binascii.hexlify(data).decode('ascii')
            print("接收的报文:{}".format(hex_data))
            apdu=self.dedcode(hex_data)["apdu"]
            if apdu[:2]=="01":
                fra_send=self.LINK_Response(apdu)
                self.Send_fr(fra_send)#报文 message
            else:
                self.rev_queue.put(apdu)
            se = AppLayer(client_socket=self.client_socket)
            se.SR()
    async def task(self):
        
        task_id = await self.input_id()
        match task_id:
            case 1:
                se = AppLayer(client_socket=self.client_socket)
                se.SR()
    def LINK_Response(self,apdu):
        dic=self.LINK_Request(apdu)
        apdu="81"+dic["piid"]+"80"+dic["time"]
        resp_time=self.MakeDateTime()
        apdu+=resp_time+resp_time
        return apdu
    def LINK_Request(self,apdu):
         dic = {}
         dic["server"]=apdu[:2]
         dic["piid"]=apdu[2:4]
         dic["type"]=apdu[4:6]
         dic["Heartbeat"]=apdu[6:10]
         dic["time"]=apdu[10:]
         return dic
    def MakeDateTime(self):
        tm = datetime.datetime.now()
        t = extract_digits(str(tm))
        week = "0"+str(datetime.date.today().weekday()+1)
        lt = t[:8]
        rt = t[8:17]
        return En_DateTime(lt+week+rt)